package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFromDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
public class UserController {

    private IUserService userService;

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @ApiOperation("新增用户")
    @PostMapping
    public ResponseEntity<String> saveUser(@RequestBody UserFromDTO userFromDTO) {
        User user = BeanUtil.copyProperties(userFromDTO, User.class);
        userService.save(user);
        return ResponseEntity.ok("新增用户成功");
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public ResponseEntity<String> removeUserById(@PathVariable("id") Long userId) {
        userService.removeById(userId);
        return ResponseEntity.ok("删除成功");
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public ResponseEntity<UserVO> queryUserById(@PathVariable("id") Long userId){
        // 1.查询用户
        User user = userService.getById(userId);
        // 2.处理vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        return ResponseEntity.ok(userVO);
    }

    @ApiOperation("根据id查询用户和地址")
    @GetMapping("/address/{id}")
    public ResponseEntity<UserVO> queryUserAndAddressById(@PathVariable("id") Long userId){
        UserVO userVO = userService.querUserAndAddressById(userId);
        return ResponseEntity.ok(userVO);
    }

    @ApiOperation("根据id集合查询用户")
    @GetMapping
    public ResponseEntity<List<UserVO>> queryUserByIds(@RequestParam("ids") List<Long> ids){
        // 1.查询用户
        List<User> users = userService.listByIds(ids);
        // 2.处理vo
        List<UserVO> userVOList = BeanUtil.copyToList(users, UserVO.class);
        return ResponseEntity.ok(userVOList);
    }

    @GetMapping("/page")
    public PageDTO<UserVO> queryUserPage(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }
}
